// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-1gpyv55g5212b580'
})

const db = cloud.database()
const _ = db.command
const villagers = require('./villagers.js').villagers

// 云函数入口函数
exports.main = async (event, context) => {
  const { uploadImages = false } = event
  
  try {
    // 创建animals集合（如果不存在）
    try {
      await db.createCollection('animals')
    } catch (err) {
      console.log('集合已存在或创建失败', err)
    }
    
    const animalsCollection = db.collection('animals')
    
    // 清空集合中的现有数据
    try {
      const countResult = await animalsCollection.count()
      const total = countResult.total
      
      if (total > 0) {
        // 分批删除数据
        const MAX_LIMIT = 100
        const batchTimes = Math.ceil(total / MAX_LIMIT)
        
        for (let i = 0; i < batchTimes; i++) {
          const documents = await animalsCollection.limit(MAX_LIMIT).get()
          const ids = documents.data.map(doc => doc._id)
          
          if (ids.length > 0) {
            await animalsCollection.where({
              _id: _.in(ids)
            }).remove()
          }
        }
      }
    } catch (err) {
      console.error('清空集合失败', err)
    }
    
    // 上传数据
    const batchSize = 20 // 每批上传的数据量
    const results = []
    
    for (let i = 0; i < villagers.length; i += batchSize) {
      const batch = villagers.slice(i, i + batchSize)
      const batchPromises = batch.map(async (villager) => {
        let fileID = null
        
        // 如果需要上传图片
        if (uploadImages) {
          try {
            // 从外部URL下载图片
            const imageUrl = villager['图片链接']
            if (imageUrl) {
              const imageResult = await cloud.downloadFile({
                url: imageUrl,
                // 10秒超时
                timeout: 10000
              })
              
              const imageBuffer = imageResult.fileContent
              
              // 上传到云存储
              const cloudPath = `villagers/${villager['名称']}.png`
              const uploadResult = await cloud.uploadFile({
                cloudPath,
                fileContent: imageBuffer
              })
              
              fileID = uploadResult.fileID
            }
          } catch (err) {
            console.error(`上传图片失败: ${villager['名称']}`, err)
          }
        }
        
        // 构建要保存的数据
        const animalData = {
          name: villager['名称'] || "",
          species: villager['种族'] || "",
          personality: villager['性格'] || "",
          birthday: villager['生日'] || "",
          gender: villager['性别'] || "",
          phrase: villager['初始口头禅'] || "",
          imageUrl: villager['图片链接'] || "",
          fileID: fileID // 云存储中的文件ID
        }
        
        // 保存到数据库
        return animalsCollection.add({
          data: animalData
        })
      })
      
      const batchResults = await Promise.all(batchPromises)
      results.push(...batchResults)
    }
    
    return {
      success: true,
      message: `成功上传 ${results.length} 条数据`,
      results
    }
  } catch (err) {
    console.error('上传数据失败', err)
    return {
      success: false,
      error: err
    }
  }
}